#include "app.h"

#define USE_LVGL

#ifdef USE_LVGL
    #include "lvgl.h" 
    #include "lv_port_disp_template.h" 
#else
    #include "st7735.h"
    #include "font.h"
#endif


char rev;
char g_data_buffer[REC_BUFF_LEN];
_GPSData GPSData;
EventGroupHandle_t uartDataCompleteHandle;

int8_t timezone_dynamic = 0;

//static bool utc2localtime(char *buf, int* localTime);

void errorLog(uint8_t code)
{
    printf("Error Code %d\n", code);
}

void app(void *pvParameters)
{
    int i = 0;
    EventBits_t rEvent;
    char *subString = NULL, *subStringNext = NULL;
    uartDataCompleteHandle = xEventGroupCreate();
    
    HAL_UART_Receive_IT(&huart2, (uint8_t *)&rev, 1);
    
    while(1)
    {
       
        rEvent = xEventGroupWaitBits(uartDataCompleteHandle,                     // 事件对象句柄
                                        RTOS_UART_EVENT,                     // 接收任务感兴趣的事件
                                        pdTRUE,                         // 退出时清除事件位
                                        pdFALSE,                         // 满足感兴趣的所有事件
                                        portMAX_DELAY);                 // 指定超时事件，一直等
        if((rEvent & RTOS_UART_EVENT) == RTOS_UART_EVENT)
        {
            if (GPSData.isGetData)
            {
                GPSData.isGetData =FALSE;
                for (i = 0 ; i <= 7 ; i++)
                {
                    if (i == 0)
                    {
                        if ((subString = strstr(GPSData.GPS_Buffer, ",")) == NULL)
                            errorLog(1);	//解析错误
                    }
                    else
                    {
                        subString++;
                        if ((subStringNext = strstr(subString, ",")) != NULL)
                        {
                            char usefullBuffer[2]; 
                            switch(i)
                            {
                                // https://www.cnblogs.com/88223100/p/GPRM_GNRMC_Transform.html
                                case 1:memcpy(GPSData.UTCTime, subString, subStringNext - subString);break;	    //1 获取UTC时间   UTC时间，hhmmss.sss格式
                                case 2:memcpy(usefullBuffer, subString, subStringNext - subString);break;       //2 获取UTC时间   状态，A=定位，V=未定位
                                case 3:memcpy(GPSData.latitude, subString, subStringNext - subString);break;	//3 获取纬度信息   ddmm.mmmmm  3107.41721
                                case 4:memcpy(GPSData.N_S, subString, subStringNext - subString);break;	        //4 获取N/S       dddmm.mmmm  12120.10943
                                case 5:memcpy(GPSData.longitude, subString, subStringNext - subString);break;	//5 获取经度信息  
                                case 6:memcpy(GPSData.E_W, subString, subStringNext - subString);break;	        //6 获取E/W
                                case 7:memcpy(GPSData.Speed, subString, subStringNext - subString);break;	    //7 地面速度 地面速率（000.0~999.9节） 
                                case 8: break;
                                case 9: break; //UTC日期，ddmmyy（日月年）

                                default:break;
                            }

                            subString = subStringNext;
                            GPSData.isParseData = TRUE;
                            if(usefullBuffer[0] == 'A')
                                GPSData.isUsefull = TRUE;
                            else if(usefullBuffer[0] == 'V')
                                GPSData.isUsefull = FALSE;
                        }
                        else
                        {
                            errorLog(2);	//解析错误
                        }
                    }	
                }
            }

//            printGpsBuffer();
            
        }
        else
        {
            printf("Event error!\n"); 
        }
        
        
        
    }
}

#define DISPLAY_ONE_LINE_LENGTH     22

#ifdef USE_LVGL
lv_obj_t* label_date;       //日期label控件
lv_obj_t* label_time;       //时间label控件
lv_obj_t* lable_gps_langtitue;
lv_obj_t* lable_gps_latitue;
lv_obj_t* lable_gps_speed;

void lv_ex_label(void)
{
    char* github_addr = "Hello LVGL";
    
    lv_obj_t * label = lv_label_create(lv_scr_act());
    lv_label_set_recolor(label, true);
    lv_label_set_long_mode(label, LV_LABEL_LONG_SCROLL_CIRCULAR); /*Circular scroll*/
    lv_obj_set_width(label, 128);
    lv_label_set_text_fmt(label, "#ff2300 %s#", github_addr);
    lv_obj_align(label, LV_ALIGN_CENTER, 0, 10);
	
    lv_obj_t * label2 = lv_label_create(lv_scr_act());
    lv_label_set_recolor(label2, true);
    lv_label_set_long_mode(label2, LV_LABEL_LONG_SCROLL_CIRCULAR); /*Circular scroll*/
    lv_obj_set_width(label2, 128);
    lv_label_set_text_fmt(label2, "#ff0034 Hello# #0000ff world !123456789#");
    lv_obj_align(label2, LV_ALIGN_CENTER, 0, -10);
}

void lv_time()
{
    lv_obj_t * label = lv_label_create(lv_scr_act());
    lv_label_set_recolor(label, true);
    lv_label_set_long_mode(label, LV_LABEL_LONG_SCROLL_CIRCULAR); /*Circular scroll*/
    lv_obj_set_width(label, 128);
    lv_label_set_text_fmt(label, "#ff2300 00:00:00#");
    lv_obj_align(label, LV_ALIGN_CENTER, 0, 10);

}

void update_gps_cb(lv_timer_t *timer) {


    char time_str[9]; // 存放格式化后的时间字符串，HH:MM:SS
    char date_str[20]; // 存放格式化后的日期字符串，YYYY-MM-DD 
    char latitue_str[32];
    char longtitue_str[32];
    char speed_str[32];
    
    int time  = 0, s, m, h;
    double speed_knot;
    double speed_kms;
    double speed_ms;
    double latitute_ddmm = 0, latitude_dddd = 0;
    double longitude_ddmm, longitude_dddd;
    float mm;
    
    
    if (GPSData.isParseData)
    {
        GPSData.isParseData = FALSE;

        time = atoi(GPSData.UTCTime);

        s = time % 100;
        m = time / 100 % 100;
        h = time / 10000 + timezone_dynamic ;
        h = h % 24;
        snprintf(time_str, sizeof(time_str), "%02d:%02d:%02d",h,m,s);
        
        if(GPSData.isUsefull)
        {
            GPSData.isUsefull = FALSE;
            latitute_ddmm = atof(GPSData.latitude);
            latitude_dddd = (int)latitute_ddmm / 100 + (latitute_ddmm - (int)latitute_ddmm / 100 * 100) / 60.0;
            snprintf(latitue_str, sizeof(latitue_str), "%s:%lf",GPSData.N_S,latitude_dddd);
            
            
            longitude_ddmm = atof(GPSData.longitude);
            longitude_dddd = (int)longitude_ddmm / 100 + (longitude_ddmm - (int)longitude_ddmm / 100 * 100) / 60.0;
            snprintf(longtitue_str, sizeof(longtitue_str), "%s:%lf",GPSData.E_W,longitude_dddd);

            timezone_dynamic = (int)longitude_dddd / 15;
            printf("timezone_dynamic=%d\n",timezone_dynamic);
            if(strcmp(GPSData.E_W, "E") == 0)
            {
                timezone_dynamic = timezone_dynamic;
          
            }
            else if(strcmp(GPSData.E_W, "W") == 0)
            {
                timezone_dynamic = -timezone_dynamic;
            }
            

            speed_knot = atof(GPSData.Speed);
            speed_kms   = speed_knot * 1.852;
            speed_ms    = speed_knot * 1.852 / 3.6;
            snprintf(speed_str, sizeof(speed_str), "%lf m/s",speed_ms);

        }
        }
    
    
    lv_label_set_text(label_time, time_str);

}


void display(void *pvParameters)
{
    lv_init();
	lv_port_disp_init();
//    lv_ex_label();

    
//     LV_IMG_DECLARE(gps);
//     lv_obj_t * img = lv_img_create(lv_scr_act());
//     lv_img_set_src(img, &gps);
//     lv_obj_set_pos(img, 0, 0);
//     lv_img_set_angle(img, 0);

    lv_timer_create(update_gps_cb, 5, NULL);
    lv_time();

    while(1)
    {
        lv_task_handler();
        vTaskDelay(5);
    }

}

#else
void display(void)
{
    int localtime = 0;
    double speed_knot;
    double speed_kms;
    double speed_ms;
    double latitute_ddmm = 0, latitude_dddd = 0;
    double longitude_ddmm, longitude_dddd;
    float mm;
    
    char buf[DISPLAY_ONE_LINE_LENGTH] = {0};
    
    ST7735_Init();
    ST7735_FillScreen(ST7735_BLACK);
    ST7735_DrawString(0,0,"GPS DISPLAY", ST7735_GREEN, ST7735_BLACK, &Font_11x18);
    // ST7735_Point(100,100, ST7735_BLUE);
    while(1)
    {
        if (GPSData.isParseData)
        {
            GPSData.isParseData = FALSE;
            utc2localtime(GPSData.UTCTime, &localtime);

            if(GPSData.isUsefull)
            {
                GPSData.isUsefull = FALSE;
                latitute_ddmm = atof(GPSData.latitude);
                latitude_dddd = (int)latitute_ddmm / 100 + (latitute_ddmm - (int)latitute_ddmm / 100 * 100) / 60.0;
                snprintf(buf, sizeof(buf), "%s:%lf",GPSData.N_S,latitude_dddd);
                ST7735_DrawString(0,20, buf, ST7735_GREEN, ST7735_BLACK, &Font_7x10);
                
                memset(buf, 0, sizeof(buf));
                
                longitude_ddmm = atof(GPSData.longitude);
                longitude_dddd = (int)longitude_ddmm / 100 + (longitude_ddmm - (int)longitude_ddmm / 100 * 100) / 60.0;
                snprintf(buf, sizeof(buf), "%s:%lf",GPSData.E_W,longitude_dddd);
                ST7735_DrawString(0,30, buf, ST7735_GREEN, ST7735_BLACK, &Font_7x10);
                timezone_dynamic = (int)longitude_dddd / 15;
                printf("timezone_dynamic=%d\n",timezone_dynamic);
                if(strcmp(GPSData.E_W, "E") == 0)
                {
                    timezone_dynamic = timezone_dynamic;
              
                }
                else if(strcmp(GPSData.E_W, "W") == 0)
                {
                    timezone_dynamic = -timezone_dynamic;
                }
                
                memset(buf, 0, sizeof(buf));
                

                speed_knot = atof(GPSData.Speed);
                speed_kms   = speed_knot * 1.852;
                speed_ms    = speed_knot * 1.852 / 3.6;
                ST7735_DrawString(0,40, "SPEED" , ST7735_GREEN, ST7735_BLACK, &Font_11x18);
                snprintf(buf, sizeof(buf), "%lf m/s",speed_ms);
                ST7735_DrawString(0,60, buf, ST7735_GREEN, ST7735_BLACK, &Font_7x10);
            }
        }
        vTaskDelay(pdMS_TO_TICKS(10));
    }
}



bool utc2localtime(char *buf, int* localTime)
{
    char time_str[7];
    int h, m, s;
    int time;
    char buffer[DISPLAY_ONE_LINE_LENGTH] = {0};
    
    
    if(buf == NULL)
    {
        return FALSE;
    }

    strncpy(time_str, buf, 6);
    time = atoi(time_str);
//    printf("time:%d\n", time);
    s = time % 100;
    m = time / 100 % 100;
    h = time / 10000 + timezone_dynamic ;
    h = h % 24;
    ST7735_DrawString(20,80, "Local  TIME", ST7735_GREEN, ST7735_BLACK, &Font_7x10);
   snprintf(buffer, sizeof(buffer), "%02d:%02d:%02d", h, m, s);
   ST7735_DrawString(30,90, buffer, ST7735_YELLOW, ST7735_BLACK, &Font_7x10);
   memset(buffer, 0, sizeof(buffer));
    
   return TRUE;
}
void printGpsBuffer(void)
{
    int localtime = 0;
    double speed_knot;
    double speed_kms;
    double speed_ms;
    double latitute_ddmm = 0, latitude_dddd = 0;
    double longitude_ddmm, longitude_dddd;
    float mm;

	if (GPSData.isParseData)
	{
		GPSData.isParseData = FALSE;
		utc2localtime(GPSData.UTCTime, &localtime);


		if(GPSData.isUsefull)
		{
			GPSData.isUsefull = FALSE;
            latitute_ddmm = atof(GPSData.latitude);
            latitude_dddd = (int)latitute_ddmm / 100 + (latitute_ddmm - (int)latitute_ddmm / 100 * 100) / 60.0;
            printf("%s->%lf\n",GPSData.N_S,latitude_dddd);
          

            longitude_ddmm = atof(GPSData.longitude);
            longitude_dddd = (int)longitude_ddmm / 100 + (longitude_ddmm - (int)longitude_ddmm / 100 * 100) / 60.0;
            printf("%s->%lf\n",GPSData.E_W, longitude_dddd);
            
            printf("GPSData.Speed = ");
            speed_knot = atof(GPSData.Speed);
            speed_kms   = speed_knot * 1.852;
            speed_ms    = speed_knot * 1.852 / 3.6;
			printf("%lf", speed_ms);
			printf("ms/s\r\n");
		}
		else
		{
			printf("GPS DATA is not usefull!\r\n");
		}
		
	}
}

#endif




